package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.common.StringHelper;
import com.example.user.myfirstapp.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Created by user on 2016/5/20.
 */
public class LoginActivity extends Activity implements View.OnClickListener {
    private Intent intent;
    private final int registerBaseCode = 1;
    private final int registerResultCode = 2;
    private TextView tv_close,tv_register;
    private Button login;
    private EditText et_user,et_pwd;
    private String userName,userPwd,password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        et_user=(EditText) findViewById(R.id.et_user);
        et_pwd=(EditText) findViewById(R.id.et_pwd);
        tv_close=(TextView) findViewById(R.id.tv_close);
        tv_close.setOnClickListener(this);
        tv_register=(TextView) findViewById(R.id.tv_register);
        tv_register.setOnClickListener(this);
        login=(Button) findViewById(R.id.btn_login);
        login.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_close:
                finish();
                //从上往下关闭
                this.overridePendingTransition(0,R.animator.silde_bottom_out);
                break;
            case R.id.tv_register:
                register();
                break;
            case R.id.btn_login:
                loginIn();
                break;
            default:
                break;
        }
    }

    private void register(){
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivityForResult(intent,registerResultCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String name = data.getStringExtra("username");
        String pwd = data.getStringExtra("userpwd");
        // 根据请求码来区别
        switch (resultCode) {
            case registerBaseCode:
                break;
            case registerResultCode:
                et_user.setText(name);
                et_pwd.setText(pwd);
                break;
            default:
                break;
        }
    }

    private void loginIn(){
        try {
            userName = et_user.getText().toString();
            userPwd = et_pwd.getText().toString();
            password = StringHelper.md5EncryptString(userPwd);//加密
            if (TextUtils.isEmpty(userName)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(userPwd)) {
                Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            }
            //显示加载中
            LoadingDialog.showLoading(this,"请稍后...");
            //和服务器的用户信息匹配
            String url = "http://"+ Constant.host+":"+Constant.port+"/api/UserInfo/GetUser/"+userName+"/"+password;
            StringRequest request = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String result) {
                            if (TextUtils.isEmpty(result) || result.equals("null")) {
                                //关闭提示语
                                LoadingDialog.closeLoading();
                                Toast.makeText(getApplicationContext(), "用户名或密码错误",
                                        Toast.LENGTH_LONG).show();

                                return;
                            }
                            else {
                                //保存用户信息到SharedPreferences
                                saveUserToSharedPreferences(result);
                                //关闭提示语
                                LoadingDialog.closeLoading();
                                //关闭当前activity
                                finish();
                                //从上往下关闭
                                LoginActivity.this.overridePendingTransition(0,R.animator.silde_bottom_out);


                                //转到用户中心页面
                                intent=new Intent(LoginActivity.this,UserCenterActivity.class);
                                startActivity(intent);
                                //从右往左切换
                                LoginActivity.this.overridePendingTransition(R.animator.slide_right_in,0);
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError err) {
                            Toast.makeText(getApplicationContext(), "网络请求失败",
                                    Toast.LENGTH_LONG).show();
                            //关闭提示语
                            LoadingDialog.closeLoading();
                        }
                    }
            );
            request.setTag("getUserByNamePwd");
            MyApplication.getHttpQueue().add(request);
        }
        catch (Exception e)
        {
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
            //关闭提示语
            LoadingDialog.closeLoading();
        }
    }

//    private void asveSharedPreferences(String name,String pwd){
//        //将用户信息保存在SharedPreferences里
//        SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
//        SharedPreferences.Editor editor = sp.edit();
//        editor.putString("username", name);
//        editor.putString("userpwd", pwd);
//        editor.commit();
//    }

    private void saveUserToSharedPreferences(String userInfoJson){
        //将用户信息保存在SharedPreferences里
        SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("userJson", userInfoJson);
        editor.commit();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("getUserByNamePwd");
    }
}
